#!/usr/bin/env python
#coding=utf8
import sys, os, urlparse, time, thread, getopt
import Log, Getconfig, Module, Downthread
import MangaBase

# global classes and modules
# global picurllist,url,name,savepathpre,mylog,chapterlist,myconfig
# global getpiclist,getchapter,picqueue

##############################################################################
# copy from http://www.cppblog.com/jinq0123/archive/2007/07/18/GetMainDir.html
# These functions get us our directory name
# Even if py2exe or another freeze tool has been used

def main_is_frozen():
    """Return ``True`` if we're running from a frozen program."""
    import imp
    return (
        # new py2exe
        hasattr(sys, "frozen") or
        # tools/freeze
        imp.is_frozen("__main__"))

def get_main_dir():
    """Return the script directory - whether we're frozen or not."""
    if main_is_frozen():
        return os.path.abspath(os.path.dirname(sys.executable))
    return os.path.abspath(os.path.dirname(sys.argv[0]))

##############################

def GetFactory(url,mangalog):
    "import appropriate module by url"
    if Module.mlist.get(urlparse.urlparse(url).hostname):
        modulepath = Module.mlist.get(urlparse.urlparse(url).hostname)
        try:
            parsemod = __import__("modules." + modulepath + ".Parser", fromlist = ['Parser'])
            return parsemod
        except  Exception, e:
            mangalog.writeLog('import downloader module fail.' + str(e),'fatal')
            sys.exit(0)
    else:
        mangalog.writeLog('import downloader module fail.','fatal')
        sys.exit(0)

def DownloadStart(Parser):
    Parser.Start()

if __name__ == '__main__':
    print 'chuan\'s manga robot, start'
    
    exportlist = False
    manganame = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'RLN:')
        if len(args) != 1:
            raise
        for o, a in opts:
            if o == '-L':
                exportlist = True
            if o == '-N' and a:
                manganame = a
        url = args[0]
    except  Exception, e:
        print 'usage: cmr.py [-R] [-L] [-N name] url'
        sys.exit()

    mylog = None
    try:
        # initialize global parameters
        mangaconfig = Getconfig.Getconfig()
        mangalog = Log.Log(mangaconfig)
        picqueue = Downthread.PicQueue()

        # download directly or output list
        if not exportlist:
            # initiate downthreads
            threadlist = []
            for i in range(0,int(mangaconfig.threadnum)):
                downloader = Downthread.Downloader(
                    picqueue=picqueue, name='No.' + str(i + 1), 
                    config = mangaconfig)
                downloader.start()
                threadlist.append(downloader)
            mangalog.writeLog('downthread initialized.')
        else:
            mangalog.writeLog('output manga page urls...')

        mangaparsermod = GetFactory(url, mangalog)
        mangaParser = mangaparsermod.Parser(url, mangaconfig,\
                                                mangalog, picqueue, manganame)
        
        thread.start_new_thread(DownloadStart, (mangaParser, ))

        while True:
            print 'type Ctrl+D or \'exit\' to end the Download/Parse.'
            input = sys.stdin.readline()
            if (not input) or (input.find('exit') != -1):
                break
            # make sure all items have been download.
            if mangaParser.end and (picqueue.getlens() == 0 or exportlist):
                break
        
        # then close downloadthreads
        if not exportlist:
            for item in threadlist:
                item.end = True
        else:
            # generate picture list export file
            print Downthread.ExportList(picqueue, mangaconfig, mangaParser.m_manganame)
        if not mangaParser.end:
            mangalog.writeLog('user break.')
        else:
            mangalog.writeLog('download finish.')
        print 'exit'
    except  Exception, e:
        if mangalog:
            mangalog.writeLog(str(e))
        else:
            print e
        sys.exit()
